package com.hgxd.controller;

import com.hgxd.annotation.OperationLogAnnotation;
import com.hgxd.entity.pojo.OperateLog;
import com.hgxd.entity.res.ResUserVo;
import com.hgxd.entity.vo.LoginVo;
import com.hgxd.mapper.OperateLogMapper;
import com.hgxd.result.Result;
import com.hgxd.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * @author wtf
 * @create 2023-10-19 9:56
 * @description :
 */
@RestController
@RequestMapping("/api")
@Slf4j
@Api(tags = "权限相关")
@CrossOrigin
public class SecurityController {

    @Resource(name="SysUserServiceImpl")
    private SysUserService sysUserService;

    @Resource
    private OperateLogMapper operateLogMapper;

    /**
     * 根据token获取登用户信息
     * @param request
     * @return
     */
    @GetMapping("/getUser")
    @ApiOperation(value = "根据token获取登用户信息",notes = "需请求头携带token")
    @OperationLogAnnotation(operModule = "权限模块-查询用户信息",operType = "查询",operContent = "根据token查询用户信息")
    public Result<Map<Integer, ResUserVo>> getUser(HttpServletRequest request){
        return Result.ok(sysUserService.getUser(request));
    }

    @OperationLogAnnotation(operModule = "权限模块-登录",operType = "登录",operContent = "用户登录")
    @PostMapping("/login")
    public Result<String> login(
            @ApiParam(name="loginVo",value = "登录vo对象",required = true)  @RequestBody LoginVo loginVo){
        log.info("访问登录");
        return Result.ok("新增成功");
    }

    /**
     * 记录用户登录日志 <p>后端内部使用，用于登录时restTemplate调用使用</p>
     * @param username
     * @param request
     * @return
     */
    @GetMapping("/setOperationForLogin")
    @ApiOperation(value = "记录用户日志",notes = "无需前端调用")
    public Boolean setOperationForLogin(String username, HttpServletRequest request){
        OperateLog operateLog = new OperateLog();
        operateLog.setUserName(username);
        operateLog.setDate(LocalDateTime.now());
        operateLog.setType("用户登录");
        operateLog.setModule("权限管理-用户登录");
        operateLog.setContent("根据用户名和密码查询用户");
        operateLog.setIp(request.getRemoteAddr());
        int insert = operateLogMapper.insert(operateLog);
        System.out.println("insert = " + insert);
        return insert > 0;
    }
}
